package com.edu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.entity.HfdUserInfo;
import com.edu.user.mapper.HfdUserInfoMapper;
import com.edu.user.service.IHfdUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.utils.JwtUtils;
import com.edu.utils.RsaUtils;
import com.edu.utils.VerifyCodeUtils;
import com.edu.vo.Result;
import com.interceptor.UserInfoInterceptor;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 曾宪霖
 * @since 2021-04-13
 */
@Service
public class HfdUserInfoServiceImpl extends ServiceImpl<HfdUserInfoMapper, HfdUserInfo> implements IHfdUserInfoService {

    @Autowired(required = false)
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    HfdUserInfoMapper hfdUserInfoMapper;

    public static final String url = "http://gw.api.taobao.com/router/rest";
    public static final String appkey = "23473071";
    public static final String secret = "951efdcc9540d2c0c1646ed6d74892e6";

    /**
     * 门户系统用户登录
     *
     * @param hfdUserInfo
     * @return
     */
    @Override
    public Result login(HfdUserInfo hfdUserInfo) {

        //判断输入是否合法
        if (hfdUserInfo == null) {
            return new Result(false, 80010, "非法参数");
        }
        if (StringUtils.isEmpty(hfdUserInfo.getPhone())) {
            return new Result(false, 80010, "请输入手机号");
        }
        if (StringUtils.isEmpty(hfdUserInfo.getPassword())) {
            return new Result(false, 80010, "请输入密码");
        }

        //查询输入的账号密码是否正确
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", hfdUserInfo.getPhone());
        HfdUserInfo user = hfdUserInfoMapper.selectOne(queryWrapper);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (user == null || !encoder.matches(hfdUserInfo.getPassword(), user.getPassword())) {
            return new Result(false, 80010, "手机号或密码错误");
        }

        //获取私钥
        PrivateKey privateKey = null;
        try {
            privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa.pri").getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //颁发令牌 30min后过期
        user.setPassword(null);
        String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 30);

        return new Result(true, 80011, "登陆成功", token);

    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @Override
    public Result sendCode(String phone) {

        //判断输入是否合法
        if (StringUtils.isEmpty(phone)) {
            return new Result(false, 80010, "非法参数");
        }

        //生成一个4位数的随机验证码
        String code = VerifyCodeUtils.generateVerifyCode(4, "0123456789");

        //发送短信(阿里大于发送短信)
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setExtend("123456");
        req.setSmsType("normal");
        req.setSmsFreeSignName("问道学院");
        req.setSmsParamString("{\"code\":\"" + code + "\"}");
        req.setRecNum(phone);
        req.setSmsTemplateCode("SMS_209190607");
        AlibabaAliqinFcSmsNumSendResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        Boolean success = rsp.getResult().getSuccess();

        //将验证码存储到redis中
        if (success) {
            //将验证码存放到redis中
            stringRedisTemplate.boundValueOps("sso:" + phone).set(code);
            //设置过期时间(10h)
            stringRedisTemplate.expire("sso:" + phone, 36000, TimeUnit.SECONDS);
            return new Result(true, 80011, "验证码发送成功");
        }

        return new Result(false, 80010, "验证码发送失败，请稍后重试");

    }

    /**
     * 门户系统用户注册
     *
     * @param hfdUserInfo
     * @return
     */
    @Override
    public Result register(HfdUserInfo hfdUserInfo) {

        //判断输入是否合法
        if (hfdUserInfo == null) {
            return new Result(false, 80010, "非法参数");
        }
        if (StringUtils.isEmpty(hfdUserInfo.getPhone())) {
            return new Result(false, 80010, "请输入手机号");
        }
        if (StringUtils.isEmpty(hfdUserInfo.getPassword())) {
            return new Result(false, 80010, "请输入密码");
        }
        if (StringUtils.isEmpty(hfdUserInfo.getCode())) {
            return new Result(false, 80010, "请输入短信验证码");
        }
        if (StringUtils.isEmpty(hfdUserInfo.getNickname())) {
            return new Result(false, 80010, "请输入昵称");
        }

        //查询手机号是否已经注册
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone", hfdUserInfo.getPhone());
        HfdUserInfo user = hfdUserInfoMapper.selectOne(queryWrapper);
        if (user != null) {
            return new Result(false, 80010, "该手机号已被注册");
        }

        //判断验证码是否正确
        String code = stringRedisTemplate.boundValueOps("sso:" + hfdUserInfo.getPhone()).get();
        if (!hfdUserInfo.getCode().equals(code)) {
            return new Result(false, 80010, "验证码错误");
        }

        //将密码加密成密文
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        hfdUserInfo.setPassword(encoder.encode(hfdUserInfo.getPassword()));

        //添加新注册用户信息
        hfdUserInfoMapper.insert(hfdUserInfo);

        return new Result(true, 80011, "账号注册成功");

    }

    /**
     * 获取当前登录的用户信息
     *
     * @return
     */
    @Override
    public Result getCurrentUser() {
        HfdUserInfo userInfo = UserInfoInterceptor.getUserInfo();
        if (userInfo == null) {
            return new Result(false, 80010, "当前未登录");
        }
        return new Result(true, 80011, "获取成功", userInfo);
    }

    /**
     * 查询所有用户信息
     *
     * @return
     */
    @Override
    public Result queryHfdUser() {
        List<HfdUserInfo> hfdUserInfoList = hfdUserInfoMapper.selectList(null);
        return new Result(true, 80011, "查询成功", hfdUserInfoList);
    }

    /**
     * 增加用户
     *
     * @param hfdUserInfo
     * @return
     */
    @Override
    public Result addHfdUser(HfdUserInfo hfdUserInfo) {
        int insert = hfdUserInfoMapper.insert(hfdUserInfo);
        if (insert > 0) {
            return new Result(true, 80011, "添加用户成功");
        } else {
            return new Result(false, 80010, "添加用户失败");
        }
    }

    /**
     * 根据user_id删除用户
     *
     * @param hfdUserInfo
     * @return
     */
    @Override
    public Result deleteHfdUserById(HfdUserInfo hfdUserInfo) {
        int delete = hfdUserInfoMapper.deleteById(hfdUserInfo);
        if (delete > 0) {
            return new Result(true, 80011, "删除用户成功");
        } else {
            return new Result(false, 80010, "删除用户失败");
        }
    }

    /**
     * 根据user_id修改用户信息
     *
     * @param hfdUserInfo
     * @return
     */
    @Override
    public Result updateHfdUserById(HfdUserInfo hfdUserInfo) {
        int update = hfdUserInfoMapper.updateById(hfdUserInfo);
        if (update > 0) {
            return new Result(true, 80011, "修改用户成功");
        } else {
            return new Result(false, 80010, "修改用户失败");
        }
    }

}
